package cn.et;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

@Controller
public class SendController {
	
	//调用sendmail的controller
	@Autowired
	RestTemplate restTemplate;
	
	@Autowired
	LoadBalancerClient load;
	
	@ResponseBody
	@GetMapping("/choose")
	public String Choose(){
		StringBuffer su= new StringBuffer();
		for(int i=0;i<=10;i++){
			ServiceInstance ss= load.choose("SENDMAIL");//从两个IDserver中选择一个 这里涉及到选择算法
			su.append(ss.getUri().toString()+"<br/>");
		}
		return su.toString();
	}
	
	@GetMapping("/sendc")
	public String sends(String emailto,String emailsubject,String emailcenter){
		//调用sendmain服务
		String controller ="/send";
		//通过注册中心客户端负载均衡 获取一台主机来调用
		try{
			controller+="?emailto="+emailto+"&emailsubject="+emailsubject+"&emailcenter="+emailcenter;
			String result=restTemplate.getForObject("http://SENDMAIL"+controller, String.class);
		}catch(Exception e){
			return "redirect:/error.html";
		}
		return "redirect:/suc.html";
	}
	
	@GetMapping("/sendclient")
	public String send(String emailto,String emailsubject,String emailcenter){
		//调用sendmain服务
		String  controller ="/sends";
		//通过注册中心客户端负载均衡 获取一台主机来调用
		try{
			HttpHeaders headers = new HttpHeaders();
			Map map=new HashMap();    
			map.put("emailto", emailto);  
			map.put("emailsubject", emailsubject);  
			map.put("emailcenter", emailcenter);  
			HttpEntity<Map> request=new HttpEntity<Map>(map, headers);  
			restTemplate.postForObject("http://SENDMAIL"+controller,request,String.class);
		
		}catch(Exception e){
			return "redirect:/error.html";
		}
		
		return "redirect:/suc.html";
	}

	
}
